package cn.gemframe.security.exception;

import cn.gemframe.constant.GemConstant;
import cn.gemframe.exception.status.GemErrorStatus;
import cn.gemframe.utils.GemStringUtlis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;


@Component
public class GemOAuth2Exception extends DefaultWebResponseExceptionTranslator{

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private ValueOperations<String, Object> valueOperations;
	
	@Override
	public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer) {
		super.setThrowableAnalyzer(throwableAnalyzer);
	}

	@Override
	public ResponseEntity<OAuth2Exception> translate(Exception exception) throws Exception {

		OAuth2Exception oAuth2Exception = new OAuth2Exception(GemErrorStatus.AUTHENTICATION_FAILED.getMsg());
		if (exception instanceof InsufficientAuthenticationException) {
			InsufficientAuthenticationException insufficientAuthenticationException = (InsufficientAuthenticationException) exception;
			String message = insufficientAuthenticationException.getMessage();
			if (GemStringUtlis.isNotBlank(message) && message.length() > 0) {
				String[] split = message.split(":");
				if (split != null && split.length == GemConstant.Number.TWO) {
					String tokenValue = split[1].trim();
					String token = String.valueOf(valueOperations.get(tokenValue));
					if (GemStringUtlis.isNotBlank(token) && GemStringUtlis.isNotBlank(tokenValue)
							&& tokenValue.equalsIgnoreCase(token)) {
						redisTemplate.delete(token);
						oAuth2Exception = new OAuth2Exception(GemErrorStatus.USER_LOGINS.getMsg());
					}
				}
			}
		}
		HttpHeaders headers = new HttpHeaders();
		headers.set("Access-Control-Allow-Origin", "*");
		return new ResponseEntity<OAuth2Exception>(oAuth2Exception, headers, HttpStatus.UNAUTHORIZED);
	}
	
}
